<template>
  <div class="add-exam-component-box">
    <div class="add-exam-component">
      <!-- 竞赛信息模块 -->
      <div class="exam-base-info-box">
        <!-- 标题 -->
        <div class="exam-base-title">
          <span class="base-title">{{ title[type] }}</span>
          <span
            class="go-back"
            @click="goBack"
          >返回</span>
        </div>
        <!-- 基本信息 -->
        <div class="exam-base-info">
          <div class="group-box">
            <div class="group-item">
              <div class="item-label required">用户组昵称</div>
              <div>
                <el-input
                  v-model="userGroupBaseInfo.nickName"
                  @change="onInfoChange"
                  @keydown.enter="saveBaseInfo"
                  style="width:420px"
                  placeholder="请填写用户组昵称"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="group-box">
            <div class="group-item">
              <div class="item-label required">用户组简介</div>
              <div>
                <el-input
                  v-model="userGroupBaseInfo.introduce"
                  @change="onInfoChange"
                  @keydown.enter="saveBaseInfo"
                  style="width:420px"
                  placeholder="请填写用户组简介"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="group-box">
            <div class="group-item">
              <el-button
                class="exam-base-info-button"
                type="primary"
                plain
                @click="saveBaseInfo"
              >保存</el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 添加用户 -->
      <div class="exam-select-question-box">
        <el-button
          class="exam-add-question"
          :icon="Plus"
          type="text"
          @click="addUserGroupUser()"
        >
          添加用户
        </el-button>
        <!-- 已经添加的用户列表 -->
        <el-table :data="userGroupUserInclude">
          <el-table-column
            prop="userId"
            label="用户id"
          />
          <el-table-column
            prop="nickName"
            label="用户昵称"
          />
          <el-table-column
            prop="phone"
            label="用户手机号"
          />
          <el-table-column
            label="操作"
            width="130px"
          >
            <template #default="{ row }">
              <el-button
                width="40px"
                type="danger"
                text="danger"
                @click="deleteUserGroupUser(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 用户组中没有添加的用户 -->
      <div>
        <el-dialog
          v-model="dialogUserGroupUserVisible"
          :before-close="handleClose"
          width="70%"
        >
          <div class="exam-list-box">
            <!-- 搜索 -->
            <div class="exam-list-title required">选择用户</div>
            <el-form inline="true">
              <el-form-item label="用户名称">
                <el-input
                  v-model.trim="queryUserListParams.nickName"
                  placeholder="请您输入要搜索的用户名称"
                  @keydown.enter="onSearch"
                />
              </el-form-item>
              <el-form-item label="手机号">
                <el-input
                  v-model.trim="queryUserListParams.phone"
                  placeholder="请您输入要搜索的手机号"
                  @keydown.enter="onSearch"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  @click="onSearch"
                  plain
                >搜索</el-button>
                <el-button
                  @click="onReset"
                  plain
                  type="info"
                >重置</el-button>
              </el-form-item>

            </el-form>

            <!-- 未添加的用户列表 -->
            <el-table
              :data="queryUserResultList"
              @select="handleRowSelect"
              @select-all="handleRowSelect"
            >
              <el-table-column type="selection"></el-table-column>
              <el-table-column
                prop="userId"
                label="用户id"
              />
              <el-table-column
                prop="nickName"
                label="用户昵称"
              />
              <el-table-column
                prop="phone"
                label="用户手机号"
              />
            </el-table>
            <div class="exam-question-list-button">
              <el-pagination
                background
                size="small"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalNum"
                v-model:current-page="queryUserListParams.pageNum"
                v-model:page-size="queryUserListParams.pageSize"
                :page-sizes="[1, 5, 10, 15, 20]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
              <div class="question-select-submit">
                <el-button
                  type="primary"
                  class="question-select-submit"
                  plain
                  @click="submitSelectUser"
                >提交</el-button>
              </div>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>


  </div>
</template>

<script setup>
  import { OPERATION_TYPE, PAGE_VALUE } from "@/constants/CRUDConstants"
  import router from '@/router'
  import { reactive, ref } from "vue"
  import { Plus } from '@element-plus/icons-vue'
  import { getUserListService } from '@/apis/cuser'
  import { useRoute } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { addUserGroupService, editUserGroupService, getUserGroupDetailService, updateUserGroupUserService } from '@/apis/cuserGroup'
  import { SPLIT } from '@/constants/constants'

  const title = {
    [OPERATION_TYPE.EDIT]: '编辑用户组',
    [OPERATION_TYPE.ADD]: '添加用户组',
  }

  let { userGroupId, type } = useRoute().query

  let isUpdate = true

  function onInfoChange() {
    isUpdate = false
  }

  // 返回
  async function goBack() {
    isUpdate || await ElMessageBox.confirm('还未保存信息 确认返回？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    router.go(-1)
  }

  function checkBaseInfo() {
    if (!userGroupBaseInfo.nickName) {
      ElMessage.error('请填写用户组名称')
      return false
    } else if (!userGroupBaseInfo.introduce) {
      ElMessage.error('请填写用户组简介')
      return false
    }
    return true
  }

  const userGroupBaseInfo = reactive({
    userGroupId: '',
    nickName: '',
    introduce: '',
  })
  async function saveBaseInfo() {
    if (!checkBaseInfo()) {
      return
    }
    if (type === OPERATION_TYPE.ADD) {
      const { data } = await addUserGroupService(userGroupBaseInfo)
      userGroupId = data
      userGroupBaseInfo.userGroupId = userGroupId
    } else {
      await editUserGroupService(userGroupBaseInfo)
    }
    isUpdate = true
    type = OPERATION_TYPE.EDIT
    ElMessage.success('保存成功')
  }

  const dialogUserGroupUserVisible = ref(false)

  /** 用户组中已经添加的用户 **/
  const userGroupUserInclude = ref([])
  async function deleteUserGroupUser(row) {
    const { userId, nickName } = row
    userGroupUserInclude.value = userGroupUserInclude.value.filter(item => item.userId !== userId)
    const data = {
      userGroupId,
      userIdList: userGroupUserInclude.value.map(item => item.userId)
    }
    await updateUserGroupUserService(data)
    ElMessage.success(`用户 ${nickName} 删除成功`)
  }


  const queryUserResultList = ref([])

  const queryUserListParams = reactive({
    pageNum: PAGE_VALUE.PAGE_NUM,
    pageSize: PAGE_VALUE.PAGE_SIZE,
    nickName: '',
    phone: '',
    excludeQuestionIdsStr: '',
  })

  async function getUserGroupDetail() {
    if (!userGroupId) {
      return
    }
    const { data } = await getUserGroupDetailService(userGroupId)
    userGroupBaseInfo.nickName = data.nickName
    userGroupBaseInfo.introduce = data.introduce
    userGroupBaseInfo.userGroupId = userGroupId
    userGroupUserInclude.value = data.userVOList
  }

  getUserGroupDetail()

  function onDelete(userGroupId) {
    console.log(userGroupId);
  }

  /** 未查询用户组中添加的用户 **/
  async function onSearch() {
    await getExcludeUserVO()
  }

  function onReset() {
    queryUserListParams.pageNum = PAGE_VALUE.PAGE_NUM
    queryUserListParams.pageSize = PAGE_VALUE.PAGE_SIZE
    queryUserListParams.nickName = ''
  }

  function handleSizeChange(value) {
    queryUserListParams.pageNum = PAGE_VALUE.PAGE_NUM
    queryUserListParams.pageSize = value
    getExcludeUserVO()
  }

  function handleCurrentChange(value) {
    queryUserListParams.pageNum = value
    getExcludeUserVO()
  }

  function handleClose() {
    dialogUserGroupUserVisible.value = false
    newUserIdList.value = []
    onReset()
  }


  const totalNum = ref(0)
  async function addUserGroupUser() {
    if (!userGroupId) {
      ElMessage.warning('请先保存用户组信息')
      return
    }
    dialogUserGroupUserVisible.value = true
    await getExcludeUserVO()
  }

  const newUserIdList = ref([])
  const handleRowSelect = (selection, row) => {
    newUserIdList.value = []
    selection.forEach(item => {
      newUserIdList.value.push(item.userId)
    })
  }

  async function submitSelectUser() {
    if (!userGroupId) {
      ElMessage.warning('请先保存用户组信息')
      return
    }
    if (!newUserIdList.value || newUserIdList.value.length === 0) {
      ElMessage.warning('请选择用户')
      return
    }
    userGroupUserInclude.value && userGroupUserInclude.value.forEach(item => {
      newUserIdList.value.push(item.userId)
    })

    const data = { userGroupId, userIdList: newUserIdList.value }
    console.log(data);

    await updateUserGroupUserService(data)
    ElMessage.success('用户添加成功')
    dialogUserGroupUserVisible.value = false
    getUserGroupDetail()
  }

  async function getExcludeUserVO() {
    if (userGroupUserInclude.value) {
      queryUserListParams.excludeQuestionIdsStr = userGroupUserInclude.value.map(item => item.userId).join(SPLIT.SEM)
    }

    const { total, rows } = await getUserListService(queryUserListParams)
    console.log(total, rows);
    queryUserResultList.value = rows
    totalNum.value = total
  }
</script>

<style lang="scss" scoped>
  .add-exam-component-box {
    height: 100%;
    overflow: hidden;
    position: relative;
  }

  .exam-list-box {
    background: #fff;
    padding: 20px 24px;

    .question-select-submit {
      margin-left: 0;
      margin-top: 20px;
      width: 100%;
    }

    .exam-list-title {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85);
      position: relative;
      padding: 15px 20px;
      padding-top: 0;

      &.required::before {
        position: absolute;
        content: '*';
        font-size: 20px;
        color: red;
        left: 10px;
      }
    }
  }

  .add-exam-component {
    width: 100%;
    background: #fff;
    padding-bottom: 120px;
    overflow-y: auto;
    box-sizing: border-box;
    height: calc(100vh - 50px);
    margin-top: -10px;

    .exam-select-question-box {

      background: #fff;
      border-bottom: 1px solid #fff;
      border-radius: 2px;
      width: 100%;

      .exam-add-question {
        font-size: 14px;
        float: right;
        margin: 10px 20px 5px 0;
      }

      .question-select-list {
        margin: 0 0 20px 0;
        height: 200px;
      }
    }

    .exam-base-info-box {
      background: #fff;
      border-bottom: 1px solid #fff;
      border-radius: 2px;
      margin-bottom: 10px;
      width: 100%;
      box-sizing: border-box;

      .exam-base-title {
        width: 100%;
        box-sizing: border-box;
        height: 52px;
        border-bottom: 1px solid #e9e9e9;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .base-title {
          font-size: 16px;
          font-weight: 500;
          color: #333333;
        }

        .go-back {
          color: #999;
          cursor: pointer;
        }
      }

      .exam-base-info {
        box-sizing: border-box;
        border-bottom: 1px solid #e9e9e9;
      }

      .mesage-list-content {
        box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.1);
        background-color: rgba(255, 255, 255, 1);
        border-radius: 10px;
        width: 1200px;
        margin-top: 20px;
      }
    }

    .group-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: calc(100% - 64px);
      margin: 24px 0;

      .group-item {
        display: flex;
        align-items: center;
        width: 100%;

        .exam-base-info-button {
          margin-left: 104px;
          width: 420px;
        }

        .item-label {
          font-size: 14px;
          font-weight: 400;
          width: 94px;
          text-align: left;
          color: rgba(0, 0, 0, 0.85);
          position: relative;
          padding-left: 10px;

          &.required::before {
            position: absolute;
            content: '*';
            font-size: 20px;
            color: red;
            left: 0px;
            top: -2px;
          }
        }
      }
    }

    .submit-box {
      display: flex;
      align-items: center;
      justify-content: center;
      background: transparent;

      &.absolute {
        position: absolute;
        width: calc(100% - 48px);
        bottom: 0;
        background: #fff;
        z-index: 999;
      }
    }
  }
</style>

<style>
  .w-e-text-container {
    min-height: 142px;
  }
</style>